const Cart = require("../model/cart.model");
const Goods = require("../model/goods.model");
const { Op } = require("sequelize");

class CartService {
  // 加入购物车
  async insertCart(product_id, user_id) {
    const res = await Goods.findOne({
      where: {
        product_id,
      },
    });
    if (res.dataValues) {
      const { product_name, product_price, product_img } = res.dataValues;
      const result = await Cart.create({
        product_id,
        user_id,
        product_name,
        product_price,
        product_img,
        quantity: 1,
        is_active: "1",
      });
      return result;
    }
  }
  // 获取购物车列表
  async getCartList_s(user_id) {
    const res = await Cart.findAll({
      where: {
        user_id,
      },
    });
    return res;
  }
  // 删除购物车商品
  async removeCart({ userId, productId }) {
    const res = await Cart.destroy({
      where: {
        user_id: userId,
        product_id: productId,
      },
    });
    return res;
  }
  // 更新购物车状态
  async updateCart_s({ userId, productId, checked, allChecked }) {
    //针对于全选按钮的操作
    if (allChecked) {
      if (allChecked === "true") {
        // 全选
        const res = await Cart.update(
          { is_active: "1" },
          {
            where: {
              user_id: userId,
            },
          }
        );
        return res;
      } else {
        const res = await Cart.update(
          { is_active: "0" },
          {
            where: {
              user_id: userId,
            },
          }
        );
        return res;
      }
    } else {
      // 单个购物车商品选中改变
      const res = await Cart.update(
        { is_active: checked },
        {
          where: {
            user_id: userId,
            product_id: productId,
          },
        }
      );
      return res;
    }
  }
}

module.exports = new CartService();
